package com.qfedu.comtrollers;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.beans.Book;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:zhengyilong
 * @email:1797344574@qq.com
 * @phone:13479394730
 * @desc:
 * @DateTime:2022/5/8 10:09
 **/
@Controller
@RequestMapping("/book")
public class BookController {

    //接受请求行数据
    @RequestMapping("/add1")
    public String add1(String name, String author, double price, HttpServletRequest request){
        System.out.println("-------book add");

        request.setAttribute("key1","value1");
        request.setAttribute("book",new Book(1,"Java","老王",30.5));
        return "tips";
    }

    @RequestMapping("/add2")
    public ModelAndView add2(String name, String author,double price){
        System.out.println("-------book add");

        //如何跳转到指定的页面
        ModelAndView modelAndView = new ModelAndView("/tips.jsp");
        modelAndView.addObject("key1","value1");
        modelAndView.addObject("book",new Book(1,"Java","老王",30.5));
        return modelAndView;
    }

    @RequestMapping("/list")
    public void list(@RequestHeader("token") String token){
        System.out.println(token);
        System.out.println("--------book list");
    }

    @RequestMapping("/update")
    @ResponseBody
    public List<Book> update(@RequestBody Book book, HttpServletResponse response) throws IOException {
        System.out.println("--------book update");
        /**
         try {
         Servlet的处理方式：使用request的输入流接收请求体数据
         ServletInputStream is = request.getInputStream();
         StringBuffer buffer = new StringBuffer();
         byte[] bs = new byte[100];
         int len = -1;
         while ((len = is.read(bs))!=-1){
         String s = new String(bs,0,len);
         buffer.append(s);
         }
         System.out.println(buffer.toString());

         } catch (IOException e) {
         e.printStackTrace();
         }
         */
        System.out.println(book);

        /**
        //使用ObjectMapper将对象转换为JSON格式字符串
        String s = new ObjectMapper().writeValueAsString(book);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.println(s);
        out.flush();
        out.close();
         */

        List<Book> books = new ArrayList<Book>();
        books.add(new Book(1,"Java","老王",30.5));
        books.add(new Book(2,"C++","老李",30.5));
        return books;
    }

}

